package com.mytrip.util;

import java.util.Random;

import javax.servlet.http.HttpServletRequest;

public class UsefulUtils{
	// 获得ip
	public static String getIpAddr(HttpServletRequest request){
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	// 随机数字
	public static int getRandomInt(int len){
		if (len <= 1) {
			return new Random().nextInt(10);
		}
		int a = Double.valueOf(Math.pow(10, (len - 1))).intValue();
		return new Random().nextInt(a * 9) + a;
	}

	// 随机字符串
	private static char[] NUM_AND_LETTER = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
			.toCharArray();

	private static int NUM_AND_LETTER_LEN = 62;

	public static String getRandomStr(int len){
		if (len <= 0) {
			return "";
		}
		Random r = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < len; i++) {
			sb.append(NUM_AND_LETTER[r.nextInt(NUM_AND_LETTER_LEN - 1)]);
		}
		return sb.toString();
	}

}
